<?php
namespace app\admin\controller;

use think\Controller;
use think\Db;
use app\admin\model\DownloadInfo as DownloadModel;
use think\Model;

class DownloadInfo extends UserAuth{
    public function index(){

        return $this->fetch('index');
    }

    /**
     * 下载列表
     * @author 吴铸峰 <1285443378@qq.com>
     * @return mixed
     */
    public function download_list(){
        if (request()->isGet()) {
            $member = (new DownloadModel())->getAll();
            $count = (new DownloadModel())->getCount();
            $this->assign('count',$count);
            $this->assign('member',$member);
        }

        return $this->fetch('download_list');
    }

    /**
     * 会员详细信息
     * @author 王柯 <wangke.email@foxmail.com>
     * @return mixed
     */
    public function download_show($id){

        $user = (new DownloadModel())->getAllDateById($id);

        $this->assign('data',$user);
        return $this->fetch('download_show');
    }

    /**
     * 详细信息
     * @author 王柯 <wangke.email@foxmail.com>
     * @return mixed
     */
    public function download_details($id){

        $user = (new DownloadModel())->getAllById($id);

        $this->assign('data',$user);
        return $this->fetch('download_details');
    }

    /**
     * 批量删除会员
     * @author 王柯 <wangke.email@foxmail.com>
     * @return array|string|\think\response\Json
     */
    public function batch_del_member(){
        if(request()->isAjax()){
            try{
                if(!empty($_POST['id'])) {
                    $arr_id = $_POST['id'];
                    $str = implode(',', $arr_id);

                    $img = [];
                    foreach ($arr_id as $key => $val) {
                        $img[$key] = Db::name('user')
                            ->where('id', $val)
                            ->field('user_images')
                            ->find();
                    }
                    $del = Db::name('user')
                        ->where('id', 'in', $str)
                        ->delete();
                    if($del){
                        if(!empty($img)){
                            foreach ($img as $key => $val){
                                if (!empty($val['user_images'])) {
                                    delImages($val['user_images']);
                                    //检查父级目录是否为空并删除空目录
                                    checkFileParentDir($val['user_images']);
                                }
                            }
                        }
                        return show(config('code.success'), '删除成功');
                    }else{
                        return show(config('code.error'),'删除失败');
                    }
                }
            }catch (\Exception $e){
                return show(config('code.error'),$e->getMessage(),[],500);
            }
        }
    }

    public function delDirAndFile($path, $delDir = FALSE) {
        if (is_array($path)) {
            foreach ($path as $subPath)
                delDirAndFile($subPath, $delDir);
        }
        if (is_dir($path)) {
            $handle = opendir($path);
            if ($handle) {
                while (false !== ( $item = readdir($handle) )) {
                    if ($item != "." && $item != "..")
                        is_dir("$path/$item") ? delDirAndFile("$path/$item", $delDir) : unlink("$path/$item");
                }
                closedir($handle);
                if ($delDir)
                    return rmdir($path);
            }
        } else {
            if (file_exists($path)) {
                return unlink($path);
            } else {
                return FALSE;
            }
        }
        clearstatcache();
    }

    //删除全部文件的方法
    public function del_download(){
        if(request()->isAjax()) {
            try {

                $path = Db::name('download_info')
                    ->where('id='.$_POST['id'])
                    ->find();
                $res = Db::name('download_info')
                    ->where('date='.$path['date'])
                    ->delete();

                if($res){
                    $this->delDirAndFile(ROOT_PATH . 'public' . DS . 'static' . DS . 'weixin' . DS . $path['file_path']);
                    rmdir(ROOT_PATH . 'public' . DS .'static' . DS . 'weixin' . DS . $path['file_path']);
                    return show(config('code.success'),'删除成功');
                }else{
                    return show(config('code.error'),'删除失败');
                }

            }catch (\Exception $e){
                return show(config('code.error'),$e->getMessage(),[],500);
            }
            }
    }


    //下载
    function download(){
        if(request()->isGet()) {
            try{
                $download = Db::name('download_info')
                            ->where('id='.$_GET['id'])
                            ->find();
            $file_url = ROOT_PATH . '/public/static/weixin/'.$download['file_path'].'/';
            if (!isset($file_url) || trim($file_url) == '') {
                return show(config('code.error'),'路径不存在');
            }
            if (!file_exists($file_url)) { //检查文件是否存在
                return show(config('code.error'),'路径不存在');
            }
                $zip = new \ZipArchive;//新建zip对象
                $path =opendir($file_url);
                $name = $download['remark'].'_'.date('Y-m-d',$download['time']/1000);
                $zipName = $name.'.zip';//zip name
            //打开zip对象
                if ($zip->open($zipName,\ZIPARCHIVE::CREATE)!==TRUE) {
                    return show(config('code.error'),'无法打开文件，或者文件创建失败');
                }else if ($zip->open($zipName, \ZipArchive::CREATE)==TRUE) {
                while (($file_name = readdir($path)) !== false){
                    //将文件遍历填充
                   if(!file_exists($file_name)){
                      $zip->addFile( $file_url.'/'.$file_name, basename($file_name));
                  }
                }
            }
                    $zip->close();
            //输入文件标签
                header("Cache-Control: public");
                header("Content-Description: File Transfer");
                header('Content-disposition: attachment; filename='.basename($zipName)); //文件名
                header("Content-Type: application/zip"); //zip格式的
                header("Content-Transfer-Encoding: binary"); //告诉浏览器，这是二进制文件
                header('Content-Length: '. filesize($zipName)); //告诉浏览器，文件大小
                ob_clean();
                flush();
                @readfile($zipName);
                unlink('./'.$zipName);
            }catch (\Exception $e){
                return show(config('code.error'),$e->getMessage(),[],500);
            }
        }
    }
}
